<?php
require_once 'relationDeletor.php';

class relation_belongs_toDeletor extends relationDeletor 
{
    
    
    public static function delete(Datatype_relation_belongs_to $fObj)
    {
            
       $deletor = parent::delete($fObj);
        
       if(!$deletor)
           return false;
        
       $deletor = $fObj->getOwner()->dropField($fObj->getForeignKey());

       if(!$deletor)
           return false;
       

       
       if($opposite = $fObj->getOpposite())
       {
           $opposite = explode('_', $opposite, 2);
           
           $oppObj = $fObj->getOwner()->getHandler()->get($fObj->getClassName());
                                 
           $oppRel = $oppObj->getFieldObject($opposite[1]);
           
          
           
           $card = $fObj->getOwner()->getHandler()->get('member_card');
           
           
           $relCardName = $oppRel->getOwner()->getClass() . '_' . $oppRel->getName();

           $args = array(array('cardname', '=', $relCardName));
                      
           $relCard = $card->getFinder()->findFirst($args);
           
           if($relCard)
           {
                $cardName = explode('_', $relCard->cardname, 2);
                $relObj = $card->getHandler()->get($cardName[0]);
                $fObj = $relObj->getFieldObject($cardName[1]);
                LEAD::requirePackage('EDO/Core/DynamicDatatypeDeletor');
                // $relCard->ldb->beginTransaction();
                $errorfree = DynamicDatatypeDeletor::delete($fObj);
                
                
                $relCard->delete();
                
                
                
                return $errorfree;               
           }
           else 
           {
                              
               $args = array(array('objectname', '=', $oppRel->getOwner()->getClass()));
               
               $card = $fObj->getOwner()->getHandler()->get('member_card');
               $cards = $card->getFinder()->findAll($args);
               
               $grid = $fObj->getOwner()->getHandler()->get('member_grid');
    
                              
               $args = array(
               array('member_card_edoid', 'IN', implode(',', $cards->getKeys())),
               array('fieldname', '=', $oppRel->getName()),
               );
               
               
               
               $grid = $grid->getFinder()->findFirst($args);
                              
               if($grid)
               {
                   $grid->delete();     
               }
                  
              $oppRel->getOwner()->dropField($oppRel->getName());
                                             
               return true;
    
           }
           
           
       }
                     
        
       return true;
       
    }
    
    
    
}